﻿using System;
using System.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using Conducido.WcfMessageLogger.Services.Behaviors.Entities;
using Conducido.WcfMessageLogger.Services.Behaviors.Entities.Config;
using Conducido.WcfMessageLogger.Services.Behaviors.Logger;

namespace Conducido.WcfMessageLogger.Services.Behaviors
{
    /// <summary>
    /// Correlator for client calls is also configurable
    /// This <see cref="IClientMessageInspector"/> is configurable just the same as the service version
    /// </summary>
    public class ClientCorrelationInspector : IClientMessageInspector
    {
        private CorrelationConfiguration _correlationConfiguration;

        /// <summary>
        /// We need it to configure the correlation
        /// </summary>
        /// <param name="correlationConfiguration"></param>
        public ClientCorrelationInspector(CorrelationConfiguration correlationConfiguration)
        {
            _correlationConfiguration = correlationConfiguration;
        }

        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            try
            {
                if (request == null || request.IsEmpty)
                {
                    return null;
                }
                if (_correlationConfiguration != null && _correlationConfiguration.ShouldCorrelate)
                {
                    var logOperator = new LogOperator(request, _correlationConfiguration);
                    Debug.WriteLine("Current Activity:" + CorrelationContext.Current.CorrelationId);

                    logOperator.AddCorrelationToConfiguredHeader();
                    request = logOperator.CopyMessage();
                }
                return null;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                throw;//TODO: fault handling
            }
            return null;
        }

        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            
        }
    }
}
